import cx from 'classnames'
import React, { useEffect, useState } from 'react'
import { IconVoice } from './Icon'
import s from './style/index.module.css'
import { useXFVoice } from './useXFVoice'
import VoiceWaving from '@/app/components/chat/xf-voice/VoiceWaving'
import { useHSVoice } from '@/app/components/chat/xf-voice/useHSVoice'
import Tooltip from '@/app/components/base/tooltip'
import Toast from '@/app/components/base/toast'

export type VoiceInputProps = {
  onRecordEnd?: (text: string) => void
  onSTTStart?: () => void
  onSTTEnd?: () => void
  className?: string
}

// const statusText = {
//   [STATUS.UNDEFINED]: "开始录音",
//   [STATUS.OPEN]: "UNDEFINED",
//   [STATUS.CLOSED]: "开始录音",
//   [STATUS.CLOSING]: "关闭连接中",
//   [STATUS.CONNECTING]: "建立连接中",
// };
const VoiceView = ({
  isRecording,
  recText,
  triggerRecord,
  className,
}: { isRecording: boolean; recText: string; triggerRecord: () => void;className?: string }) => {
  return (
    <div className={cx(s.container, className)}>
      <div className={s.record_panel}>
        <div
          className={cx(s.record_popup, {
            [s.vs_hide]: true, // !isRecording,
          })}
        >
          <div className={s.popup_header}>
            <div className={s.recording_indicator}></div>
            <span>正在聆听...</span>
          </div>
          <div className={s.popup_body}>{recText}</div>
        </div>
        <Tooltip
          selector="record-tip"
          htmlContent={
            <div>
              <div>{isRecording ? '停止语音输入' : '语音输入'}</div>
            </div>
          }
        >
          <span className={cx(`${s.icon_wrapper} w-8 h-8 cursor-pointer rounded-md`, { [s.recording]: isRecording })}
            onClick={triggerRecord}
          >
            {!isRecording ? <IconVoice className={cx(s.icon, { [s.recording]: isRecording })}/> : <VoiceWaving/>}
          </span>

        </Tooltip>
      </div>
    </div>
  )
}
const XFVoice: React.FC<VoiceInputProps> = (props) => {
  const { onRecordEnd } = props
  const {
    isRecording: _isRecording,
    recText,
    triggerRecord,
  } = useXFVoice({
    onRecordEnd,
    onError: (e) => {
      Toast.notify({
        type: 'error',
        message: e.message || '语音出错了',
      })
    },
  })
  const isRecording = _isRecording()
  return (
    <VoiceView className={`${s.hs_voice} xz-chat-voice-view`} recText={recText} isRecording={isRecording} triggerRecord={triggerRecord}/>
  )
}
const HSVoice: React.FC<VoiceInputProps> = (props) => {
  const {
    onRecordEnd,
    onSTTStart,
    onSTTEnd,
  } = props
  const {
    isRecording: _isRecording,
    recText,
    triggerRecord,
  } = useHSVoice({
    onRecordEnd,
    onSTTEnd,
    onSTTStart,
    onError: (e) => {
      Toast.notify({
        type: 'error',
        message: e.message || '语音出错了',
      })
    },
  })
  const isRecording = _isRecording()
  return (
    <VoiceView recText={recText} isRecording={isRecording} triggerRecord={triggerRecord}/>
  )
}
const VoiceInput: React.FC<VoiceInputProps> = (props) => {
  const [count, setCount] = useState(0)
  useEffect(() => {
    const keyBinding = {
      xf: '!',
      hs: '@',
      ...window.__voiceSwitchKeyBinding,
    }
    const handleKeyUp = (e: KeyboardEvent) => {
      if (!e.shiftKey || !e.ctrlKey || !e.key)
        return

      const key = e.key.toLowerCase()
      if (key === keyBinding.xf) {
        e.preventDefault()
        setCount(0)
        document.documentElement.classList.remove('xz-chat-voice_type-1')
        document.documentElement.classList.add('xz-chat-voice_type-0')

        console.log('XZ-Chat: switch STT to XF')
        return
      }
      if (key === keyBinding.hs) {
        e.preventDefault()
        setCount(1)
        document.documentElement.classList.remove('xz-chat-voice_type-0')
        document.documentElement.classList.add('xz-chat-voice_type-1')
        console.log('XZ-Chat: switch STT to HS')
      }
    }
    window.__setVoiceInput = (key: string) => {
      if (key === 'hs') {
        setCount(1)
        console.log('XZ-Chat: switch STT to HS')
        return
      }
      setCount(0)
      console.log('XZ-Chat: switch STT to XF')
    }
    document.addEventListener('keyup', handleKeyUp)
    return () => {
      document.removeEventListener('keyup', handleKeyUp)
    }
  }, [])
  return count % 2 === 0 ? <XFVoice {...props} /> : <HSVoice {...props} />
}
export default VoiceInput
